﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
using System.Runtime.InteropServices.Marshalling;
using TestFileManager.Models;

namespace TestFileManager.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileManagerController : ControllerBase
    {
        [HttpPost]
        public async Task<ActionResult<string>> UploadFile([FromForm]FileModel model)
        {
            try
            {
                string path = Path.Combine("Images", model.File.FileName);

                if (!Directory.Exists("Images"))
                    Directory.CreateDirectory("Images");

                using (var fs = new FileStream(path, FileMode.Create))
                    await model.File.CopyToAsync(fs);

                return Ok("http://localhost:5178/api/FileManager/" + model.File.FileName);
            } catch(Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [HttpGet("{fileName}")]
        public async Task<FileContentResult> GetFile(string fileName)
        {
            try
            {
                string path = Path.Combine("Images", fileName);

                if (!Directory.Exists("Images"))
                    Directory.CreateDirectory("Images");

                byte[] file = System.IO.File.ReadAllBytes(path);

                return new FileContentResult(file, "image/png");
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
